package t10086.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import t10086.Configure.InitConfig;
import t10086.Configure.SocketConfig;
import t10086.Data.Pop.PopMsg;
import t10086.Data.Pop.PopType;
import t10086.Data.Robot.RobotInfo;
import t10086.Data.Robot.RobotQueue;
import t10086.Data.Robot.RobotType;
import t10086.Model.Messages.MessageType;
import t10086.WorkThread.*;
import t10086.WorkThread.Shared.Client.Client;
import t10086.Data.Broadcast;
import t10086.WorkThread.Shared.DataBuffer;
import t10086.WorkThread.Shared.ClientMap;

import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;

@Controller
public class WebSocketController {
    // 定时广播消息
    private final SimpMessagingTemplate messagingTemplate;
    private final SocketConfig socketConfig;
    @Autowired
    public WebSocketController(SimpMessagingTemplate messagingTemplate, SocketConfig socketConfig) {
        this.messagingTemplate = messagingTemplate;
        this.socketConfig = socketConfig;
    }

    @MessageMapping("/hello")
    public void hello(Message<String> message) {
        System.out.println(message.getPayload());
    }


    @Scheduled(fixedRate = 300)
    public void sendPeriodicMessage() {
        synchronized (DataBuffer.class){//锁住全局信息
            Broadcast broadcast = DataBuffer.getBroadcast();
            broadcast.autoUpdate();//更新队列信息
            messagingTemplate.convertAndSend("/broadcast/test", broadcast);//websocket广播
            broadcast.clearPopQueue();
            sendBroadcast(broadcast);//socket广播
        }
    }
    public void  sendBroadcast(Broadcast broadcast) {
        Map<InetSocketAddress, Client> map = ClientMap.getClients();
        InetSocketAddress self = new InetSocketAddress(InitConfig.selfIp, socketConfig.getPort());
        map.forEach((inetSocketAddress, client) -> {
            if(client.getRole() != RobotType.ROBOT){
                return;
            }
            t10086.Model.Messages.Message message = new t10086.Model.Messages.Message();
            message.setSender(self);
            message.setReceiver(client.getSocketAddress());
            message.setNext(client.getSocketAddress());
            message.setType(MessageType.BROADCAST);
            message.setData(broadcast);

            ThreadPoolManager.submitTask(new MsgConvertHandler(
                                         new LinkedList<>(
                                         Collections.singletonList(message))));
        });
    }
}
